 var table ,form ,laypage ,layer ,element ,laydate ,upload ,treetable ,colorpicker//时间组件
$(function(){
    layui.config({
        base: '/res/layui/module/'
    }).extend({
        treetable: 'treetable-lay/treetable'
    }).use(['table','form','laypage','layer', 'element', 'laydate','upload','treetable','colorpicker'], function () {
    	table = layui.table;
        form=layui.form;
        laypage = layui.laypage ;//分页
        layer = layui.layer ;//弹层
        element = layui.element; //元素操作
        laydate = layui.laydate; //时间组件 
        treetable=layui.treetable;
        upload = layui.upload;
        colorpicker = layui.colorpicker;

        renderTable()                
        //搜索按钮事件
        $('#btn-search').click(function () {
            var keyword = $('#edt-search').val();
            var searchCount = 0;
            $('#tabledata').next('.treeTable').find('.layui-table-body tbody tr td').each(function () {
                $(this).css('background-color', 'transparent');
                var text = $(this).text();
                if (keyword != '' && text.indexOf(keyword) >= 0) {
                    $(this).css('background-color', 'rgba(250,230,160,0.5)');
                    if (searchCount == 0) {
                        treetable.expandAll('#tabledata');
                        $('html,body').stop(true);
                        $('html,body').animate({scrollTop: $(this).offset().top - 150}, 500);
                    }
                    searchCount++;
                }
            });
            if (keyword == '') {
                layer.msg("请输入搜索关键字", {icon: 5});
            } else if (searchCount == 0) {
                layer.msg("没有匹配结果", {icon: 5});
            }
        });
		  //编辑表单验证
		form.verify({
			  fname: function(value, item){ //名称验证
					if(validate.isBlank(value))
					{
						return "请输入类型名称！";
					}
				    if(!validate.maxLength(value,20)){
				      return '类型名称长度不能超过50个字符';
				    }
			  }
		  	  ,fdescription: function(value, item)//描述验证
			  {
				    if(!validate.maxLength(value,200))
				    {
				      return '描述长度不能超过200个字符';
				    }
			  }
			});  
  	  //监听行工具事件
  	  table.on('tool(auth-table)', function(obj){
  	    var data = obj.data;
  	    if(obj.event === 'del'){
  		      layer.confirm('确认要删除该数据?', function(index){
  			    	//异步删除数据
	  		    	var requestData = {"id": data.id};
	          	  	$.ajax({
	      	           url: "/equipmentType/deleteEquipmentType.do",               //请求地址
	      	           type: "POST",              //请求类型
	      	           data:formatParam(requestData),              //请求数据
	      	           timeout: 200000,                //请求超时时间(毫秒)
	      	           headers: setHeader(),
	      	           success:function(res){         //请求成功
	      	        	   if(res.status == 200)
	      	  				{
	      	        		     layer.msg(res.resultMsg, {icon: 6});//提示删除成功
	  							//obj.del();//删除表格数据行
	  							 renderTable();					
	      	  				}else if(res.status == 666){
	      	  				  TIMEOUT(); 
	      	  		        }else{
	      	  					layer.msg(res.resultMsg, {icon: res.icon});
	      	  				}
	      	        	   form.render();      
	                    }
	                 })
	                 layer.close(index);//关闭确认框
	                 return false;
  			      }); 

  	    }else if(obj.event === 'edit'){
  	    	//编辑按钮事件
  	    	var num = obj.data;
		    var fullindex=layer.open({
		        type: 1,
		        area: ['690px', '420px'],
		        fix: false, //不固定
		        maxmin: true,
		        shadeClose: true,
		        shade:0.4, //遮罩层
		        title: ['设备类型编辑','background:#1E9FFF;color:#fff'],
		        content: $('#form_edit')
		    });
		    $("#id").val(num.id);
		    $("#pid").val(num.pid);
		    $("#pname").val(num.pName);
		    $("#name").val(num.name);	    		   	
		    $("#remarks").val(num.remarks);		    
		  //上级菜单选择
			var setting = {
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true,
						idKey : "id",
						pIdKey: "pid"
					},
					key: {
						url:'none'
					}
				},
				callback: {
					onClick: onClick,
					onAsyncSuccess: function(event, treeId, treeNode, msg) {
					    $.fn.zTree.getZTreeObj(treeId).expandAll(true);//异步加载完成后展开tree
					}
				}
			};
			$.ajax({
		        url: "/equipmentType/getList.do",               //请求地址
		        type: "POST",              //请求类型
		        data:{},              //请求数据
		        timeout: 200000,                //请求超时时间(毫秒)
		        headers: setHeader(),
		        success:function(res){         //请求成功
		     	   if(res.status == 200){
		     		  var zNodes=res.resultData.data
		     		  var zTree = $.fn.zTree.init($("#treeDemo"), setting ,zNodes);
		     		 zTree.expandAll(true);//节点展开
				   }else if(res.status == 666){
					   TIMEOUT(); 
			       }else{
	  					layer.msg(res.resultMsg, {icon: res.icon});
	  				} 
		       }
		    })//上级菜单选择end
		    form.render();
  	     }
  	     form.render();
  	  });
	  //编辑表单提交事件
	  form.on('submit(editInfo)', function(data){
		    this.blur();//防止点回车，按钮重复点击
		  	var loadIndex = layer.load(1);//显示加载层
		  	var requestData = formToJsonObj("form_edit", []);
		  	$.ajax({
		           url: "/equipmentType/editEquipmentType.do",               //请求地址
		           type: "POST",              //请求类型
		           data:formatParam(requestData),              //请求数据
		           timeout: 200000,                //请求超时时间(毫秒)
		           headers: setHeader(),
		           success:function(res){         //请求成功
		        	   if(res.status == 200)
		  				{
		    				layer.msg(res.resultMsg, {icon: res.icon},function(){
		    					layer.closeAll();//关闭加载层
		    					 renderTable();		
							}); 					
		  				}else if(res.status == 666){
		  				   TIMEOUT(); 
		  		        }else{
		  					layer.msg(res.resultMsg, {icon: res.icon});
		  				}  
	              }
	           })
			return false; //阻止表单跳转。
		});
  	  //折叠按钮事件
      $('#zd').click(function () {
    	  var btn = $(this);
          if(btn.attr('title') == '全部折叠')
          {
        	  treetable.foldAll('#tabledata');
        	  $(this).attr('title','全部展开');
        	  $(this).removeClass("layui-icon-triangle-d");
        	  $(this).addClass("layui-icon-triangle-r");
          }else
          {
        	  treetable.expandAll('#tabledata');
        	  $(this).attr('title','全部折叠');
        	  $(this).removeClass("layui-icon-triangle-r");
        	  $(this).addClass("layui-icon-triangle-d");
          }
      });
   });
	
})
 var renderTable = function () {
	 $.ajax({
	        url: "/equipmentType/getList.do",               //请求地址
	        type: "POST",              //请求类型
	        data:{},              //请求数据
	        timeout: 200000,                //请求超时时间(毫秒)
	        headers: setHeader(),
	        success:function(res){         //请求成功
	     	   if(res.status == 200){
	     		 layer.load(2);
	     	     treetable.render({
	     	     	 data:res.resultData.data,
	     	     	 treeColIndex: 2,//树形图标显示在第1列
	     	         treeSpid: '1000001',
	     	         treeIdName: 'id',
	     	         treePidName: 'pid',               
	     	         treeDefaultClose: false,
	     	         elem: '#tabledata',
	     	         height: $(window).height()-200,		   
	     	         loading: true,
	     	         page: false,
	     	         cols: [[
	     	        	 {field: 'id', title: 'id', align:'left',hide:true,width:50},
	     	        	 {field: 'xuhao', title: '序号',  align:'center', type:'numbers',width:50},
	     	             {field: 'name', minWidth: 200, title: '类型名称'},	     	             
	     	             {field: '', title: '操作', align:'center',width:180,fixed:'right',
	     	            	 templet: function(data){
	     							return '<div class="layui-btn-group">'+
	     		                            // '<a href="/res/page/Management/Community_form.html?id='+data.id+'" class="layui-btn layui-btn-normal layui-btn-xs" lay-event="look">编辑/查看</a>'+
	     	                                   '<a href="javascript:;" class="layui-btn layui-btn-normal layui-btn-xs BTNSHOW BTNSHOW_EDIT" lay-event="edit">编辑</a>'+        
	     							           '<a href="javascript:;" class="layui-btn layui-btn-danger layui-btn-xs BTNSHOW BTNSHOW_DELETE" lay-event="del" >删除</a>'+	                             
	     	                               '</div>'   
	     						}	 
	     	             }
	     	         ]],
	     	         done: function () {
	     	             layer.closeAll('loading');
	     	            permissionFUN()//功能按钮权限
	     	           if(res.status!=200){
		   		    		if(res.status == 666){
		   		    		  TIMEOUT(); 
		   	  		        }else{
		                   	  $(".layui-none").text(res.resultMsg)
		   	  		        }  
	                   }
	     	             
	     	         }
	     	     });
			   }else{
	  					layer.msg(res.resultMsg, {icon: res.icon});
	  				} 
	       }
	 })    	
 }
function onClick(e, treeId, treeNode) {
		$("#pname").val(treeNode.name);
		$("#pid").val(treeNode.id);
		hideMenu();	
}
function showMenu() {
var cityObj = $("#pname");
var cityOffset = $("#pname").offset();
$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
$('ul.ztree').width(cityObj.width());//设置下拉菜单宽度	
$("body").bind("mousedown", onBodyDown);
}
function hideMenu() {
$("#menuContent").fadeOut("fast");
$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
	hideMenu();
}
}